const express = require('express');
const fileUpload = require('express-fileupload');
const fs = require('fs').promises;
const path = require('path')
const uploadFilesPath = path.resolve(__dirname, 'uploadFiles')
const app = express();


// 上传静态文件 
app.use('/uploadFiles', express.static(uploadFilesPath));

app.use('/appupdate/update', function(req, res, next){
  fs.readdir(uploadFilesPath)
    .then(ret=>{
      res.send(ret.filter(f=>/\d+\.zip$/.test(f)).map(fileName=>{
        return {
          url: `http://127.0.0.1:3006/uploadFiles/${fileName}`,
          versionStamp: parseInt(fileName.match(/(\d+)\.\w+$/)[1])
        }
      }));
    })
});

app.use(fileUpload())
app.post('/upload', function(req, res, next) {
  let file;
  let uploadPath;
  console.log(req.files)
  console.log(req.file)
  if (!req.files || Object.keys(req.files).length === 0) {
    res.status(400).send('No files were uploaded.');
    return;
  }

  console.log('req.files >>>', req.files);
  file = req.files.file;
  uploadPath = `${uploadFilesPath}/${ Date.now()}.` + file.name.match(/\.(\w+)$/)[1]

  file.mv(uploadPath, function(err) {
    if (err) {
      return res.status(500).send(err);
    }
    res.send(`
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>处理结果</title>
      </head>
      <body>
        <p style="color:green"><b>上传成功：${uploadPath}</b></p>
        <p><b id="timer"></b></p>
        <script>
          function runTimmer(num){
            if (num > 0) {
              document.getElementById('timer').innerText= num + '秒后返回';
            }
            if (num > 1) {
              setTimeout(()=>{
                runTimmer(num - 1);
              }, 1000);
            } else {
              window.history.go(-1);
              window.location.reload();
            }
          }
          runTimmer(5);
        </script>
      </body>
      </html>
    `);
  });
});

app.get('/', function(req, res, next){
  res.sendFile(path.resolve(__dirname, 'index.html'));
})


app.listen(3006, function(err){
  console.log('server is listening at 127.0.0.1:3006');
})